import { PluginConfig } from '../interface/plugin-config';

/**
 * iframe插件上飘窗控制器
 *
 * @export
 * @class OpenPluginController
 */
export class OpenPluginController {
    /**
     * 容器
     *
     * @memberof OpenPluginController
     */
    readonly wrapper: HTMLIbzTopDrawerWrapperElement;

    /**
     * iframe呈现容器
     *
     * @private
     * @memberof OpenPluginController
     */
    readonly iframeWrapper: HTMLIbzPluginIframeWrapperElement;

    /**
     * 配置
     *
     * @type {PluginConfig}
     * @memberof OpenPluginController
     */
    readonly config: PluginConfig;

    /**
     * 回调
     *
     * @private
     * @type {*}
     * @memberof OpenPluginController
     */
    private resolve?: any;

    /**
     * Creates an instance of OpenPluginController.
     * @param {PluginConfig} config
     * @param {*} [style]
     * @memberof OpenPluginController
     */
    constructor(config: PluginConfig) {
        this.config = config;
        // 初始化飘窗容器
        this.wrapper = document.createElement('ibz-top-drawer-wrapper');
        this.wrapper.isCache = config.isCache;
        this.wrapper.headerTitle = config.title;
        // 初始化iframe容器
        this.iframeWrapper = document.createElement('ibz-plugin-iframe-wrapper');
        this.iframeWrapper.setUrl(config.url, config.params);
        // 挂载
        this.wrapper.appendChild(this.iframeWrapper);
        document.body.appendChild(this.wrapper);
    }

    init(): void {
        this.iframeWrapper.addEventListener('closeIframe', (data: any) => {
            this.wrapper.close();
            if (this.resolve) {
                this.resolve(data);
            }
        });
        this.iframeWrapper.addEventListener('hiddenIframe', (data: any) => {
            this.wrapper.hiddenDrawer();
            if (this.resolve) {
                this.resolve(data);
            }
        });
    }

    /**
     * 显示
     *
     * @return {*}  {Promise<any>}
     * @memberof OpenPluginController
     */
    open(): Promise<any> {
        return new Promise((resolve: any) => {
            this.wrapper.showChange();
            this.resolve = resolve;
        });
    }

    /**
     * 隐藏
     *
     * @memberof OpenPluginController
     */
    hidden() {
        this.wrapper.hiddenDrawer();
    }

    /**
     * 显示
     *
     * @memberof OpenPluginController
     */
    show() {
        this.wrapper.showDrawer();
    }

    /**
     * 关闭
     *
     * @memberof OpenPluginController
     */
    close(): void {
        this.wrapper.remove();
    }

    /**
     * 向iframe发送消息
     *
     * @param {*} data
     * @memberof OpenPluginController
     */
    sendMessage(data: any): void {
        this.iframeWrapper.sendIframeMessage(data);
    }
}
